import 'package:get/get.dart';

///
/// 当前语音状态
///
enum XRecordStatus {
  /// 空闲状态
  idle,

  /// 录音中
  recording,

  /// 恢复录制
  resumeRecord,

  /// 暂停录音
  pausedRecord,

  /// 停止录音
  stopRecord,
}

///
/// 语音按钮背景圆弧高度
///
const kOnnxVoiceBgOvalHeight = 120.0;

///
/// 状态变更，局部刷新组件
///
class OnnxWidgetsNotifireController extends GetxController {
  static OnnxWidgetsNotifireController get to => Get.find<OnnxWidgetsNotifireController>();

  /// 进行语音录制状态
  final recordStatus = XRecordStatus.idle.obs;
  // 状态缓存，避免不必要的更新
  XRecordStatus? _cachedRecordStatus;

  /// 语音识别文本
  final recognizedText = ''.obs;

  /// 文本缓存，避免不必要的更新
  String? _cachedRecognizedText;

  ///
  /// 更新录制状态
  ///
  void updateRecordStatus(XRecordStatus value) {
    if (_cachedRecordStatus != value) {
      _cachedRecordStatus = value;
      recordStatus.value = value;
    }
  }

  ///
  /// 更新识别文本（带缓存优化）
  ///
  void updateRecognizedText(String text) {
    if (_cachedRecognizedText != text) {
      _cachedRecognizedText = text;
      recognizedText.value = text;
    }
  }

  ///
  /// 逐步更新识别文本（打印机效果）
  ///
  void updateRecognizedTextWithTypewriterEffect(String newText) {
    final currentText = _cachedRecognizedText ?? '';

    // 如果新文本比当前文本长，说明有新内容需要显示
    if (newText.length > currentText.length && newText.startsWith(currentText)) {
      // 逐步显示新增的字符
      final additionalText = newText.substring(currentText.length);
      _animateTextAddition(currentText, additionalText);
    } else {
      // 直接更新文本
      updateRecognizedText(newText);
    }
  }

  ///
  /// 清空识别文本
  ///
  void clearRecognizedText() {
    _cachedRecognizedText = '';
    recognizedText.value = '';
  }

  ///
  /// 动画显示新增文本
  ///
  void _animateTextAddition(String baseText, String additionalText) {
    if (additionalText.isEmpty) return;

    // 每次添加一个字符，创建打字机效果
    for (int i = 0; i <= additionalText.length; i++) {
      Future.delayed(Duration(milliseconds: i * 50), () {
        final displayText = baseText + additionalText.substring(0, i);
        if (_cachedRecognizedText != displayText) {
          _cachedRecognizedText = displayText;
          recognizedText.value = displayText;
        }
      });
    }
  }
}
